<?php

namespace app\admin\controller;

use app\common\model\AdminMenu;
use app\common\model\AdminRole;
use app\common\model\AdminUser;
use think\Db;
use think\Exception;
use utils\Result;

class Admin extends Common
{
    /**
     * 个人信息
     * @return string|Result
     * @throws \Exception
     */
    public function info()
    {
        if ($this->request->isPost()){

            $param = $this->request->param();

            $data = [
                'nickname'  =>  $param['nickname'],
                'email'     =>  $param['email'],
            ];

            if (!empty($param['pass']) && !empty($param['repass'])){
                $data['password'] = password($param['pass']);
            }

            $update = AdminUser::update($data,['id' => session('aid') ]);


            if ($update) return Result::success('修改成功');

            return Result::error('修改失败');

        }

        $info = $this->getInfo();

        $this->assign(compact('info'));

        return $this->view->fetch();
    }

    /**
     * 编辑管理员
     * @return string
     * @throws \Exception
     */
    public function edit()
    {
        $this->AuthCheck();
        return $this->view->fetch();
    }

    /**
     * 角色管理
     * @return \think\response\View
     */
    public function role()
    {
        $this->AuthCheck();
        if ($this->request->isPost()){

            $list = Db::name('admin_role')->select();

            return Result::layui($list);

        }
        return view();
    }

    /**
     * 添加角色
     * @return string
     * @throws \Exception
     */
    public function addRole()
    {
        $this->AuthCheck();
        if ($this->request->isPost()){

            $param = $this->request->param();

            $param['limit_array'] = implode(',',$param['auth']);

            if ((new AdminRole())->allowField(true)->save($param)) return Result::success('新增成功');

            return Result::error('新增失败');

        }

        $menu = AdminMenu::all();

        $menu = $this->recursive_make_tree($menu);

        $this->assign(compact('menu'));

        return $this->view->fetch();
    }

    /**
     * 编辑角色
     * @return string
     * @throws \Exception
     */
    public function editRole()
    {
        $this->AuthCheck();

        if ($this->request->isPost()){

            $data = $this->request->param();

            if (session('aid') != 1 && $data['id'] == 1) return Result::error('禁止修改当前角色(原因：您不是超级管理员');

            $data['limit_array'] = implode(',',$data['auth']);

            if ((new AdminRole())->allowField(true)->save($data,['id' => $data['id'] ])) return Result::success('修改成功');

            return Result::error('修改失败');

        }
        $id = $this->request->get('id');

        $info = AdminRole::get($id);

        $menu = $this->createMenu(AdminMenu::all(),explode(',',$info['limit_array']));

        $menu = $this->recursive_make_tree($menu);

        $this->assign(compact('menu','info'));

        return $this->view->fetch();
    }

    /**
     * 删除角色
     * @return bool|Result
     */
    public function delRole()
    {
        if (!$this->request->isPost()) return Result::error('非法请求');

        if (true !== $this->AuthCheck(false)) return Result::error('权限不足，无法删除');

        $id = $this->request->post('id');

        if ($id == 1) return Result::error('超级管理员无法删除');

        $destroy = AdminRole::destroy($id);

        if ($destroy) return Result::success('删除成功');

        return Result::error('删除失败');

    }

    /**
     * 对比两个数组是否有相同的值
     * @param $arr1
     * @param $arr2
     * @param string $arr1_key
     * @param string $arr2_key
     * @return mixed
     */
    private function createMenu($arr1,$arr2,$arr1_key = 'id',$arr2_key = '')
    {
        for ($i = 0;$i <count($arr1);$i++){
            for ($j = 0;$j<count($arr2);$j++){
                if ($arr2_key == ''){
                    if ($arr1[$i][$arr1_key] == $arr2[$j]){
                        $arr1[$i]['checked'] = true;
                        break;
                    }
                }else{
                    if ($arr1[$i][$arr1_key] == $arr2[$j][$arr2_key]){
                        $arr1[$i]['checked'] = true;
                        break;
                    }
                }
            }
        }
        return $arr1;
    }

    /**
     * 管理员管理
     * @return string|Result
     * @throws \Exception
     */
    public function user()
    {
        $this->AuthCheck();
        if ($this->request->isPost()){
            $list = AdminUser::alias('au')
                        ->join('admin_role ar','ar.id = au.role_id')
                        ->field('au.*,ar.role_name')
                        ->select();
            return Result::layui($list);
        }
        return $this->view->fetch();
    }

    /**
     * 新增管理员
     * @return string|Result
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addUser()
    {
        $this->AuthCheck();
        if ($this->request->isPost()){
            $param = $this->request->param();

            $model = new AdminUser();

            $info = $model->where('login_name',$param['login_name'])->find();

            if ($info) return Result::error('该管理员账号已存在');

            $param['password'] = password($param['password']);

            $insert = $model->allowField(true)->save($param);

            if ($insert) return Result::success('新增成功');

            return Result::error('新增失败');

        }
        $role = AdminRole::where('id','<>',1)->all();

        $this->assign(compact('role'));

        return $this->view->fetch();
    }

    /**
     * 编辑用户
     * @return string|Result
     * @throws \Exception
     */
    public function editUser()
    {
        if ($this->request->isPost()){

            $param = $this->request->param('data');

            $data = [
                'nickname'  =>  $param['nickname'],
                'email'     =>  $param['email'],
            ];

            if (!empty($param['pass']) && !empty($param['repass'])){
                $data['password'] = password($param['pass']);
            }

            $update = AdminUser::update($data,['id' => $this->request->post('id') ]);


            if ($update) return Result::success('修改成功');

            return Result::error('修改失败');

        }

        $info = AdminUser::get($this->request->get('id'));

        $this->assign(compact('info'));

        return $this->view->fetch();
    }

    /**
     * 删除管理员
     * @return Result
     */
    public function delUser()
    {
        if (!$this->request->isPost()) return Result::error('非法请求');

        if (true !== $this->AuthCheck(false)) return Result::error('权限不足，无法删除');

        $id = $this->request->post('id');

        if ($id == 1) return Result::error('超级管理员无法删除');

        $destroy = AdminUser::destroy($id);

        if ($destroy) return Result::success('删除成功');

        return Result::error('删除失败');

    }
}
